package com.ruitaowang.core.aspect;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Created by neal on 11/22/16.
 */

@Aspect
@Component
public class WebLogAspect {
    protected final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(getClass());
    @Pointcut("execution(public * com.ruitaowang.*.view..*Controller.*(..))")
    public void webLog(){}
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes == null){
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        if(request.getRequestURL().indexOf("login")<0){
            LOGGER.debug("URL : " + request.getRequestURL().toString());
            LOGGER.debug("HTTP_METHOD : " + request.getMethod());
            LOGGER.debug("IP : " + request.getRemoteAddr());
            LOGGER.debug("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            LOGGER.debug("ARGS : " + Arrays.toString(joinPoint.getArgs()));
            //LOGGER.debug("ARGS JSON : " + JSON.toJSON(joinPoint.getArgs()));
        }
    }
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        LOGGER.debug("RESPONSE : " + ret);
    }
}